package day24;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//针对集合做序列化 List<StudentInfo>
public class Demo12 {
    static List<StudentInfo> list=new ArrayList<>();
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        one:
        while(true) {
            System.out.println("1.新增学生");
            System.out.println("2.查询学生");
            System.out.println("3.删除学生");
            System.out.println("其他:结束");
            int n = sc.nextInt();
            switch (n) {
                case 1: add();break;
                case 2: select();break;
                case 3: del();break;
                default: break one;
            }
        }
    }
    public static void add() throws IOException, ClassNotFoundException {
        //先读取原来的集合
        input();
        System.out.println("目前的集合对象包括:");
        for(StudentInfo info:list){
            System.out.println("ID:"+info.id+"  性别:"+info.sex+"  电话:"+info.phone);
        }
        System.out.println("请输入需要添加的学生信息");
        System.out.print("ID:");
        int id = sc.nextInt();
        System.out.print("性别:");
        String name = sc.next();
        System.out.print("电话:");
        String phone = sc.next();
        list.add(new StudentInfo(id,name,phone));
        //序列化保存最新集合文件
        output();
    }
    public static void select() throws IOException, ClassNotFoundException {
        //反序列化:读取最新数据
        if(list.isEmpty()) {
            input();
        }
        System.out.println("目前的集合对象包括:");
        for(StudentInfo info:list){
            System.out.println("ID:"+info.id+"  性别:"+info.sex+"  电话:"+info.phone);
        }
    }
    public static void del() throws IOException, ClassNotFoundException {
        select();
        System.out.print("请输入要删除的对象的ID:");
        int id = sc.nextInt();
        list.removeIf(list -> (list.id).equals(id));
        output();
    }
    public static void input() throws IOException, ClassNotFoundException {//反序列化
        try(FileInputStream fis=new FileInputStream("d://a//list.abc");
            ObjectInputStream ois=new ObjectInputStream(fis)){
            list=(List<StudentInfo>)ois.readObject();
        }catch (FileNotFoundException e){
            System.out.println("你是第一次使用 没有文件");
        } catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void output() throws IOException {//序列化
        FileOutputStream fos=new FileOutputStream("d://a//list.abc");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(list);
        oos.close();
        fos.close();
    }
}
